<script setup lang="ts">
import SkuForm from "./SkuForm.vue";
import SpuForm from "./SpuForm.vue";
import { ref, watch, onBeforeUnmount } from "vue";
import { getSpuPageList, deleteSpu } from "@/api/product/spu";
import type { SpuDataPageQueryReq, SpuData } from "@/api/product/spu/type";
import { listSkuBySpu } from "@/api/product/sku";
import type { SkuData, SkuDataResp } from "@/api/product/sku/type";
import type { BasePageReq, BasePageResp } from "@/api/baseType";
import categoryConfigStore from "@/store/modules/categoryConfig";
import { ElMessage } from "element-plus";
let categoryConfig = categoryConfigStore();
//场景1列表页，场景2新增修改页，场景3添加sku
const scene = ref<number>(1);
//表格数据
const tableData = ref<SpuData[]>([]);
//分页请求参数
const pageReq = ref<BasePageReq>({
  page: 1,
  limit: 3,
});
//查询请求参数
const queryParam = ref<SpuDataPageQueryReq>({});
//分页器参数
const paginationParam = ref<BasePageResp>({
  total: 0,
  size: 0,
  current: 0,
  searchCount: false,
  pages: 0,
});
//子组件SpuForm实例
let spuFormRef = ref<any>();
//子组件SkuForm实例
let skuFormRef = ref<any>();
//存储全部的SKU数据
let skuDataList = ref<SkuData[]>([]);
//控制模态框显示隐藏
let dialogVisible = ref<boolean>(false);
//查询
const pageQuery = async () => {
  const res = await getSpuPageList(pageReq.value, queryParam.value);
  if (res.code === 200) {
    tableData.value = res.data.records;
    //解构res.data
    const { total, size, current, searchCount, pages } = res.data;
    //将解构后的数据赋值给分页器
    paginationParam.value = { total, size, current, searchCount, pages };
  }
};
//页码变更时
const handleCurrentChange = (current: number) => {
  pageReq.value.page = current;
  pageQuery();
};
//页数变更时
const handleSizeChange = (size: number) => {
  pageReq.value.limit = size;
  pageReq.value.page = 1;
  pageQuery();
};
//监听三级分类id
watch(
  () => categoryConfig.category3Id,
  () => {
    tableData.value = [];
    if (!categoryConfig.category3Id) {
      return;
    }
    queryParam.value.category3Id = categoryConfig.category3Id;
    pageQuery();
  },
);
//添加spu
const addSpu = () => {
  scene.value = 2;
  categoryConfig.isDisabled = true;
  spuFormRef.value.initAddSpuData(categoryConfig.category3Id);
};
//修改spu
const editSpu = (row: SpuData) => {
  scene.value = 2;
  categoryConfig.isDisabled = true;
  spuFormRef.value.initSpuData(row);
};
//查看spu
const viewSpu = async (row: SpuData) => {
  const res: SkuDataResp = await listSkuBySpu(row.id);
  if (res.code === 200) {
    skuDataList.value = res.data;
    dialogVisible.value = true;
  }
};
//添加sku
const addSku = (row: SpuData) => {
  scene.value = 3;
  categoryConfig.isDisabled = true;
  skuFormRef.value.initSkuData(
    row,
    categoryConfig.category1Id,
    categoryConfig.category2Id,
  );
};
//删除Spu
const reqDeleteSpu = (id: number) => {
  const res: any = deleteSpu(id);
  if (res.code === 200) {
    ElMessage.success("删除成功");
    if (tableData.value.length <= 1) {
      pageReq.value.page = pageReq.value.page - 1;
    }
    pageQuery();
  } else {
    ElMessage.error(res.message);
  }
};
//路由组件销毁的时候
onBeforeUnmount(() => {
  categoryConfig.$reset();
});
//自定义事件，子组件传值给父组件
const changeScene = (obj: any) => {
  //解构
  const { params, num } = obj;
  scene.value = num;
  categoryConfig.isDisabled = false;
  if (params === "add") {
    pageReq.value = {
      page: 1,
      limit: 3,
    };
    pageQuery();
  } else if (params === "update") {
    pageQuery();
  }
};
</script>

<template>
  <div>
    <Category :scene="scene" />
    <el-card style="margin: 10px 0">
      <div v-show="scene === 1">
        <el-button
          type="primary"
          icon="Plus"
          :disabled="!categoryConfig.category3Id"
          @click="addSpu"
          >添加SPU</el-button
        >
        <el-table style="margin: 10px 0" border :data="tableData">
          <el-table-column label="序号" type="index" width="80px" />
          <el-table-column label="SPU名称" prop="spuName" width="240px" />
          <el-table-column
            label="SPU描述"
            prop="description"
            show-overflow-tooltip
          />
          <el-table-column label="操作" width="480px">
            <template #default="{ row }">
              <el-button
                type="success"
                icon="Plus"
                size="small"
                title="添加SKU"
                @click="addSku(row)"
              ></el-button>
              <el-button
                size="small"
                type="warning"
                icon="Edit"
                title="编辑SPU"
                @click="editSpu(row)"
              ></el-button>
              <el-button
                size="small"
                type="primary"
                icon="View"
                title="查看SPU"
                @click="viewSpu(row)"
              ></el-button>
              <!-- 气泡确认框 -->
              <el-popconfirm
                :title="`确定要删除${row.spuName}吗？`"
                @confirm="reqDeleteSpu(row.id)"
              >
                <template #reference>
                  <el-button
                    size="small"
                    type="danger"
                    icon="Delete"
                    title="删除SPU"
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          :current-page="paginationParam?.current"
          :page-size="paginationParam?.size"
          :page-sizes="[10, 15, 20]"
          :background="true"
          layout="prev, pager, next, jumper,->,total, sizes"
          :total="paginationParam?.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <SpuForm
        ref="spuFormRef"
        v-show="scene === 2"
        @changeScene="changeScene"
      ></SpuForm>
      <SkuForm
        ref="skuFormRef"
        v-show="scene === 3"
        @changeScene="changeScene"
      ></SkuForm>
      <!-- 查看sku信息的对话框 -->
      <el-dialog
        v-model="dialogVisible"
        title="SKU列表"
        width="50%"
        destroy-on-close
      >
        <el-table :data="skuDataList" border>
          <el-table-column label="名称" prop="skuName" />
          <el-table-column label="价格" prop="price" />
          <el-table-column label="重量" prop="weight" />
          <el-table-column label="图片">
            <template #default="{ row }">
              <img :src="row.skuDefaultImg" style="width: 100px" />
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
    </el-card>
  </div>
</template>

<style lang="scss" scoped></style>
